import { Decoder, Encoder, Options } from './models.js';

const BOMChar = '\uFEFF';

/**
 * StripBOMDecoderWrapper 解码器
 */
export class StripBOMDecoderWrapper implements Decoder {
  private decoder: Decoder;
  private pass: boolean;
  private options: Options;

  constructor(decoder: Decoder, options?: Options) {
    this.decoder = decoder;
    this.pass = false;
    this.options = options || {};
  }

  write(buffer: Buffer | Uint8Array): string {
    const buf = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);
    let res = this.decoder.write(buf);
    if (this.pass || !res) return res;

    if (res[0] === BOMChar) {
      res = res.slice(1);
    }

    this.pass = true;
    return res;
  }

  end(): string | undefined {
    return this.decoder.end();
  }
}

/**
 * PrependBOMEncoderWrapper 编码器
 */
export class PrependBOMEncoderWrapper implements Encoder {
  private readonly encoder: Encoder;
  private addBOM: boolean;

  constructor(encoder: Encoder, options?: Options) {
    this.encoder = encoder;
    this.addBOM = true;
  }

  write(str: string): Buffer {
    if (this.addBOM) {
      str = BOMChar + str;
      this.addBOM = false;
    }

    return this.encoder.write(str);
  }

  end(): Buffer | undefined {
    return this.encoder.end();
  }
}
